﻿using Azure.Core;
using Common.Models;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Wallpaper.Data.Context;
using Wallpaper.Data.Dal;
using Wallpaper.Data.IDal;
using Wallpaper.Models.DTOs.Base;
using Wallpaper.Models.DTOs.Responses;
using Wallpaper.Models.Entities;
using Wallpaper.Services.IService;

namespace Wallpaper.Services.Service
{
    public class UserFavoriteService : IUserFavoriteService
    {

        readonly IUserFavoriteDal _userFavoriteDal;
        readonly WallpaperDbContext _dbContext;

        public UserFavoriteService(IUserFavoriteDal userFavoriteDal, WallpaperDbContext dbContext)
        {
            _userFavoriteDal = userFavoriteDal;
            _dbContext = dbContext;
        }


        /// <summary>
        /// 创建用户收藏
        /// </summary>
        /// <param name="wallpaperId"></param>
        /// <param name="userId"></param>
        /// <returns></returns>
        public async Task<bool> AddFavoriteAsync(string wallpaperId, string userId)
        {
            UserFavorite userFavorite = new UserFavorite();
            userFavorite.WallpaperId = wallpaperId;
            userFavorite.UserId = userId;
           return await _userFavoriteDal.CreateEntityAsync(userFavorite);
        }


        /// <summary>
        /// 用移除收藏
        /// </summary>
        /// <param name="wallpaperId"></param>
        /// <param name="userId"></param>
        /// <returns></returns>
        public async Task<bool> RemoveFavoriteAsync(string wallpaperId, string userId)
        {
            var result = await _dbContext.UserFavorites
                .Where(f => f.WallpaperId == wallpaperId && f.UserId == userId)
                .ExecuteDeleteAsync();
            return result > 0;
        }


        /// <summary>
        /// 获取用户收藏
        /// </summary>
        /// <param name="query"></param>
        /// <param name="userId"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<PagedResult<DownloadRecordUserResponse>> UserFavorites(QueryRequest query, string userId)
        {
            var queryable =
                                      (from favorite in _userFavoriteDal.GetDbSet<UserFavorite>()
            .Where(r => r.UserId == userId)
                                       join user in _userFavoriteDal.GetDbSet<User>()
                                           on favorite.UserId equals user.Id
                                       join wallpaper in _userFavoriteDal.GetDbSet<Wallpapers>()
                                           on favorite.WallpaperId equals wallpaper.Id
                                       join category in _userFavoriteDal.GetDbSet<Category>()
                                           on wallpaper.CategoryId equals category.Id
                                       select new DownloadRecordUserResponse
                                       {
                                           Id = favorite.Id,
                                           WallpaperId = wallpaper.Id,
                                           FileUrl = wallpaper.FileUrl,
                                           TypeName = category.Name,
                                           CreateAt = favorite.CreatedAt

                                       });
            if (!string.IsNullOrEmpty(query.Keyword))
            {
                queryable = queryable.Where(w => w.TypeName.Equals(query.Keyword));
            }
            var totalCount = await queryable.CountAsync();

            // 3. 添加排序（按下载时间倒序）
            queryable = queryable.OrderByDescending(x => x.CreateAt);

            var items = await queryable
            .Skip((query.Page - 1) * query.PageSize)
            .Take(query.PageSize)
                .ToListAsync();

            return new PagedResult<DownloadRecordUserResponse>
            {
                Page = query.Page,
                PageSize = query.PageSize,
                TotalCount = totalCount,
                Items = items
            };
        }
    }
}
